import { IOptions, ISvgOptions } from "./types";
import {
  generateClazzTsxContent,
  generateFunTsxContent,
  generateHtmlContent,
  generateLessContent,
  generateIconfontContent,
  generateSymbolContnt,
} from "./templates";
import { checkAndMakeDirPath, readSvgFiles } from "./tools";

const fs = require("fs");
const path = require("path");

export function generateIconfont(options: IOptions) {
  options.outputValue = options.outputValue || "/dist";
  const { isPure, inputValue, outputValue, isDeep, id, isClazz } = options;
  const inputPathList: string[] = inputValue?.split("/").filter(Boolean) || [];
  const outputPathList: string[] = outputValue.split("/").filter(Boolean);
  const fileName: string = inputPathList[inputPathList.length - 1];
  const svgId = id || fileName;
  const inputPath = path.join(process.cwd(), ...inputPathList);
  const outputPath = path.join(process.cwd(), ...outputPathList);
  let symbolsList: ISvgOptions[] = [];
  if (fs.existsSync(inputPath) && fs.statSync(inputPath).isDirectory()) {
    const svgs = readSvgFiles(path.join(inputPath), {
      isPure,
      isDeep,
    });
    symbolsList = [...symbolsList, ...svgs];
    outputIconfonts({ svgId, outputPath, isClazz, symbolsList });
  } else {
    throw new Error("input is not a directory");
  }
  // 输出文件
}
// 输出文件
async function outputIconfonts(options: {
  outputPath: any;
  symbolsList: ISvgOptions[];
  isClazz?: boolean;
  svgId: string;
}) {
  const { outputPath, isClazz, symbolsList, svgId } = options;
  const iconfontContent = generateIconfontContent(
    symbolsList.map(generateSymbolContnt).join(""),
    svgId
  );
  const idList = symbolsList.map((item) => item.name) || [];
  // 1 输出iconfont.js文件
  checkAndMakeDirPath(outputPath);
  fs.writeFileSync(path.join(outputPath, `iconfont.js`), iconfontContent);
  // 2 输出React组件
  const iconPath = path.join(outputPath, "Icon");
  if (!fs.existsSync(iconPath) || !fs.statSync(iconPath).isDirectory()) {
    fs.mkdirSync(iconPath);
  }
  // 2.1 输出.tsx文件
  const tsxContent = isClazz
    ? generateClazzTsxContent(idList)
    : generateFunTsxContent(idList);
  fs.writeFileSync(path.join(outputPath, "Icon", "index.tsx"), tsxContent);
  // 2.2 输出.less文件
  const lessContent = generateLessContent();
  fs.writeFileSync(path.join(outputPath, "Icon", "index.less"), lessContent);
  // 3 输出index.html文件，可以看到图标，点击图标复制type
  const htmlContent = generateHtmlContent(idList);
  fs.writeFileSync(path.join(outputPath, "index.html"), htmlContent);
}
